package com.jintu.portal.service.datadriver.parser.impl;

import com.alibaba.fastjson.JSONObject;
import com.jintu.portal.cache.RedisHelper;
import com.jintu.portal.pojo.submit.DataResponse;
import com.jintu.portal.service.datadriver.parser.DataParser;
import com.jintu.portal.service.datadriver.parser.ParserCommon;
import com.jintu.portal.service.datadriver.pojo.MsgRespCode;
import com.jintu.portal.service.datadriver.pojo.Response;
import com.jintu.portal.service.datadriver.pojo.SysRespCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author very
 */
@Slf4j
@Component
public class TaoBaoParser implements DataParser {

    @Resource(name = "redisHelper")
    private RedisHelper redisHelper;

    @Override
    public boolean parseAndSaveData(String data, DataResponse dataResponse, Integer userId) {
        if (StringUtils.isBlank(data)) {
            return ParserCommon.isDataSourceIsEmpty(dataResponse);
        }
        Response response = JSONObject.parseObject(data, Response.class);
        String retCode = response.getRetCode();
        if (SysRespCode.QUERY_SUCCESS.getCode().equals(retCode)) {
            String msgCode = response.getRetInfo().getCode();
            if (MsgRespCode.SEARCH.getCode().equals(msgCode)) {
                log.info("请求淘宝 数据成功返回授权信息");
                String tradeNo = ((JSONObject) response.getRetInfo().getMessage()).getString("tradeNo");
                if(StringUtils.isBlank(tradeNo)){
                    log.error("淘宝认证接口返回tradeNo为空");
                } else {
                    ParserCommon.setResponseSuccessAndCacheTradeNo(dataResponse, redisHelper, tradeNo);
                }
            }
        }
        dataResponse.setResponseJson(JSONObject.parseObject(JSONObject.toJSONString(response)));
        return false;
    }
}
